Crate mock_instant

source ·
Expand description

§mock_instant

This crate allows you to test Instant/Duration code, deterministically per thread.

If cross-thread determinism is required, enable the sync feature:

mock_instant = { version = "0.2", features = ["sync"] }

It provides a replacement std::time::Instant and std::time::SystemTime that uses a deterministic thread-local ‘clock’

NOTE: if this is enabled then all tests will use the same singleton MockClock source


You can swap out the std::time::Instant with this one by doing something similar to:

#[cfg(test)]
use mock_instant::Instant;

#[cfg(not(test))]
use std::time::Instant;

or for a std::time::SystemTime

#[cfg(test)]
use mock_instant::{SystemTime, SystemTimeError};

#[cfg(not(test))]
use std::time::{SystemTime, SystemTimeError};

§Example

use std::time::Duration;

let now = Instant::now();
MockClock::advance(Duration::from_secs(15));
MockClock::advance(Duration::from_secs(2));

// its been '17' seconds
assert_eq!(now.elapsed(), Duration::from_secs(17));

§Mocking a SystemTime

use std::time::Duration;

let now = SystemTime::now();
MockClock::advance_system_time(Duration::from_secs(15));
MockClock::advance_system_time(Duration::from_secs(2));

// its been '17' seconds
assert_eq!(now.elapsed().unwrap(), Duration::from_secs(17));

Structs§

  • A simple deterministic Instant wrapped around a modifiable Duration
  • A Mock clock
  • A simple deterministic SystemTime wrapped around a modifiable Duration
  • An error returned from the duration_since and elapsed methods on SystemTime, used to learn how far in the opposite direction a system time lies.

Constants§